package cn.xierongsheng.mailserve.service;

import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import freemarker.template.Configuration;
import freemarker.template.Template;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private Configuration freemarkerConfiguration;

    /**
     * 发送邮件至Hr邮箱表示感谢
     */
    public void sendEmailToHr(String to, String name) throws MessagingException, IOException, TemplateException {
        // 准备数据模型
        Map<String, Object> model = new HashMap<>();
        model.put("name", name);
        model.put("sendTime", new Date());


        StringWriter out = new StringWriter();
        Template template = freemarkerConfiguration.getTemplate("email-template.html"); // 邮件模板
        template.process(model, out);

        // 发送邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setTo(to);
        helper.setFrom("447618716@qq.com");
        helper.setSubject("感谢您对我的青睐与关注");
        helper.setText(out.toString(), true); // true 表示这是一个HTML邮件
        mailSender.send(mimeMessage);
    }

    /**
     * 发送邮件至自己邮箱查看相关信息
     */
    public void sendEmailToSelf(String to, String name, String phone, String subject, String content) throws MessagingException, IOException, TemplateException {
        // 准备数据模型
        Map<String, Object> model = new HashMap<>();
        model.put("to", to);
        model.put("name", name);
        model.put("phone", phone);
        model.put("subject", subject);
        model.put("content", content);
        model.put("sendTime", new Date());


        StringWriter out = new StringWriter();
        Template template = freemarkerConfiguration.getTemplate("email-to-self-template.html"); // 邮件模板
        template.process(model, out);

        // 发送邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setTo("447618716@qq.com");
        helper.setFrom("447618716@qq.com");
        helper.setSubject("当前消息来自" + to);
        helper.setText(out.toString(), true); // true 表示这是一个HTML邮件
        mailSender.send(mimeMessage);
    }
}